/**
 * 
 */
package cn.ad.server.web.servlet.v2.requesthandler;

import cn.ad.server.common.utils.BrowserUtils;
import cn.ad.server.common.utils.IPUtils;
import cn.ad.server.web.log.entity.AdActiveEventLog;
import cn.ad.server.web.log.entity.AdTrackingEventLog;
import cn.ad.server.web.servlet.v2.parser.TalkingDataRequestParser;
import cn.ad.server.web.spring.model.AdRequest;
import cn.ad.server.web.spring.model.TalkingDataRequest;
import cn.ad.server.web.spring.model.dactive.DactiveAdResponse;
import cn.ad.server.web.spring.service.actions.context.IPContext;
import cn.ad.server.domain.IPDetail;
import cn.ad.server.domain.ad.GuidValueObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;

/**
 * TalkingData
 * @author wangwei
 */
public class TalkingDataRequestHandler extends DactiveRequestHandler{
	
	private static Logger LOGGER = LoggerFactory.getLogger(TalkingDataRequestHandler.class);

	/**
	 * 
	 */
	public TalkingDataRequestHandler() {
		setParser(new TalkingDataRequestParser());
	}
	
	/* (non-Javadoc)
	 * @see cn.ad.server.web.servlet.v2.AdserverRequestServlet#handleExceptionResponse(java.lang.Exception, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void handleExceptionResponse(Exception e, HttpServletResponse response) {
		if(!(e instanceof NullResponseException)){
			LOGGER.error("处理TalkingData Request时出现异常，异常原因:{}", e.getMessage(), e);
		}
		response.setStatus(204);
		response.setContentLength(0);
	}

	@Override
	public AdActiveEventLog populate(AdRequest req, DactiveAdResponse res) {
		if(!(req instanceof TalkingDataRequest)){
			return null;
		}
		TalkingDataRequest request = (TalkingDataRequest)req;
		AdActiveEventLog eventLog = new AdActiveEventLog();
		if(res.getGuidData()!=null){
			populate2(request, res,eventLog);
			eventLog.setIdfa(request.getIdfa());
			eventLog.setChannel_id(request.getChannelID());		
			eventLog.setBchid(res.getFillChannelId());
			eventLog.setAvid(request.getAvid());
			return eventLog ;
		}
		
		eventLog.setEventType(AdTrackingEventLog.MOBILEAPP_ACTIVE);
		eventLog.setRequestTimestamp(request.getRequestTimestamp());
		eventLog.setServerId(IPUtils.getHostID());
		eventLog.setGuid(request.getGuid());
		eventLog.setExceptionType(res.getStatus());
		eventLog.setRequestIp(request.getIp());
		eventLog.setAdspaceId(0);
		eventLog.setAdFormat(0);
		eventLog.setCreativeHeight(0);
		eventLog.setCreativeWidth(0);
		eventLog.setUa(request.getUa());
		eventLog.setIp(request.getIp());
		eventLog.setMuniqueType(res.getMuniqueType());
		eventLog.setMuniqueId(res.getMuniqueId());
		eventLog.setMobOps("");
		eventLog.setBrand("");
		eventLog.setModel("");
		//0 - 未知  1 - android 2 - ios  3- windows',
		if("android".equals(request.getOs())){
			eventLog.setOs(String.valueOf(1));
		}else if("ios".equals(request.getOs())){
			eventLog.setOs(String.valueOf(2));
		}else if("windows".equals(request.getOs())){
			eventLog.setOs(String.valueOf(3));
		}else{
			eventLog.setOs(String.valueOf(0));
		}
		eventLog.setConnType(0);
		eventLog.setDeviceType(0);
		eventLog.setScreenHeight(0);
		eventLog.setScreenWidth(0);
		eventLog.setLatitude("");
		eventLog.setLongitude("");
		eventLog.setCountryId(0);
		eventLog.setStateId(0);
		eventLog.setCityId(0);
		eventLog.setAreaId(0);
		eventLog.setBrowser("");
		eventLog.setCampaignId(0);
		eventLog.setStateId(0);
		eventLog.setCreativeId(0);
		eventLog.setTemplateId(0);
		eventLog.setMaterialId(0);
		eventLog.setIncome(0);
		eventLog.setPayment(0);
		eventLog.setImei(request.getImei());
		eventLog.setMac(request.getMac());
		eventLog.setMac1("");
		eventLog.setIdfa(request.getIdfa());
		eventLog.setAaid("");
		eventLog.setAnid(request.getAndroidid());
		eventLog.setUdid("");
		eventLog.setDuid("");
		eventLog.setImeisha1("");
		eventLog.setDpidsha1("");
		eventLog.setMacsha1("");
		eventLog.setImeimd5(request.getImei_md5());
		eventLog.setDpidmd5(request.getAndroidid_md5());
		eventLog.setMacmd5(request.getMac_md5());
		eventLog.setOpenUdid("");
		eventLog.setCustomId("");
		eventLog.setAdxType(0);
		eventLog.setChannel_id(req.getChannelID());
		
		eventLog.setBchid(res.getFillChannelId());
		eventLog.setAvid("");
		
		return eventLog;
	}
	
	
	/**
	 * 存在guid对象。
	 * @param request
	 * @param response
	 * @param event
	 */
	@Deprecated
	void populate2(AdRequest request, DactiveAdResponse response,AdActiveEventLog event){
		TalkingDataRequest req = (TalkingDataRequest)request;
		GuidValueObject guidObj = response.getGuidData();
		
	 	event.setRequestTimestamp(req.getRequestTimestamp());
		event.setRequestIp(req.getIp());
		event.setServerId(IPUtils.getHostName());
		event.setPlatformId(0);
		event.setAdxType(0);
		event.setChannel_id(req.getChannelID());
		
		event.setGuid(req.getGuid());
		event.setGuid(req.getGuid());
		event.setUa(req.getUa());
		event.setBrowser(BrowserUtils.getBrowser(req.getUa()));
		
		IPDetail ipDetail = IPContext.instance().getIPDetail(IPUtils.convertIPToLong(guidObj.getIp()));
		if (ipDetail != null) {
			event.setCountryId(ipDetail.getCountryId());
			event.setStateId(ipDetail.getStateId());
			event.setCityId(ipDetail.getCityId());
			event.setAreaId(ipDetail.getDistrictId());
		}
		event.setEventType(AdTrackingEventLog.MOBILEAPP_ACTIVE);
		
		//设置事件异常状态
		event.setExceptionType(response.getStatus());
		event.setAdFormat(guidObj.getFid());
		event.setTemplateId(guidObj.getTemplateId());
//		event.setCampaignId(res.getCampaignId()); TODO ...
		event.setAdspaceId(guidObj.getAid());
		event.setMuniqueType(String.valueOf(guidObj.getMuniqueType()));
		event.setMuniqueId(guidObj.getMuniqueId());
		event.setMobOps(String.valueOf(guidObj.getOperator()));
		event.setBrand(guidObj.getBrand());
		event.setModel(guidObj.getPlatform());
		event.setOs(String.valueOf(guidObj.getOs()));
		event.setConnType(guidObj.getNetwork());
		event.setDeviceType(guidObj.getDeviceType());
		event.setLatitude(String.valueOf(guidObj.getLatitude()));
		event.setLongitude(String.valueOf(guidObj.getLongitude()));
		event.setIp(guidObj.getIp());
		event.setStrategyId(guidObj.getSid());
		event.setCreativeId(guidObj.getCid());
		event.setMaterialId(guidObj.getMid());
		
		if (!StringUtils.isEmpty(guidObj.getDeviceSize()) && guidObj.getDeviceSize().contains("*")) {
			String[] d = guidObj.getDeviceSize().split("\\*");
			event.setScreenWidth(Integer.valueOf(d[0]));
			event.setScreenHeight(Integer.valueOf(d[1]));
		}
//				event.setCreativeHeight(res.getCreativeHeight());TODO ...
//				event.setCreativeWidth(res.getCreativeWidth());
		event.setMac(guidObj.getMac());
		event.setMac1(guidObj.getMac1());
		event.setImei(guidObj.getImei());
		event.setAnid(guidObj.getAnid());
		event.setAaid(guidObj.getAaid());
		event.setIdfa(guidObj.getIdfa());
		event.setUdid(guidObj.getUdid());
		event.setDuid(guidObj.getDuid());

		event.setImeisha1(guidObj.getImeisha1());
		event.setDpidsha1(guidObj.getDpidsha1());
		event.setMacsha1(guidObj.getMacsha1());
		event.setImeimd5(guidObj.getImeimd5());
		event.setDpidmd5(guidObj.getDpidmd5());
		event.setMacmd5(guidObj.getMacmd5());
		event.setCustomId(guidObj.getCustomId());
		event.setOpenUdid(guidObj.getOpenUdid());
		
		event.setIncome(0);
		event.setPayment(0);
	}
}
